import { useState, useEffect, useRef } from 'react';
import '@/index.css';
import styles from './home.module.css';
// 导入SearchBox组件
import SearchBox from '@/components/SearchBox';
// 导入LazyImage组件
import LazyImage from '@/components/Image';

const Home = () => {
  // 商品列表数据
  const [products, setProducts] = useState([
    { id: 1, title: '李宁 T恤 跑步系列速干排汗', price: 185, image: 'https://picsum.photos/id/1/300/400', seller: '天猫 李宁旗舰店' },
    { id: 2, title: 'Do-win/多威 征途三代', price: 219, image: 'https://picsum.photos/id/2/300/300', seller: '识货专享' },
    { id: 3, title: '苹果 iPhone 16 Pro 5G', price: 5799, image: 'https://picsum.photos/id/3/300/350', seller: '天猫 苹果旗舰店', tag: '国家补贴' },
    { id: 4, title: '特步 薄底香菜 网面减震', price: 174, image: 'https://picsum.photos/id/4/300/280', seller: '天猫 特步旗舰店' },
    { id: 5, title: '华为 主动降噪耳机', price: 799, image: 'https://picsum.photos/id/5/300/320', seller: '天猫 华为旗舰店' },
    { id: 6, title: 'Nike Air Max 运动鞋', price: 899, image: 'https://picsum.photos/id/6/300/380', seller: '天猫 Nike旗舰店' },
    { id: 7, title: 'Adidas 休闲卫衣', price: 359, image: 'https://picsum.photos/id/7/300/290', seller: '天猫 Adidas旗舰店' },
    { id: 8, title: '小米 智能手表', price: 1299, image: 'https://picsum.photos/id/8/300/330', seller: '天猫 小米旗舰店' },
  ]);

  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const observerRef = useRef(null);

  // 新增搜索处理函数
  const handleQuery = (query) => {
    console.log('搜索关键词:', query);
    // 这里可以添加搜索逻辑
    if (query) {
      // 例如跳转到搜索页面
      window.location.hash = `#/search?query=${encodeURIComponent(query)}`;
    }
  };

  // 加载更多商品
  const loadMoreProducts = () => {
    if (loading) return;

    setLoading(true);
    // 模拟API请求延迟
    setTimeout(() => {
      const newProducts = Array.from({ length: 4 }, (_, index) => ({
        id: products.length + index + 1,
        title: `商品 ${products.length + index + 1}`,
        price: Math.floor(Math.random() * 1000) + 100,
        image: `https://picsum.photos/id/${products.length + index + 10}/300/${280 + Math.floor(Math.random() * 120)}`,
        seller: '示例商家',
        tag: Math.random() > 0.7 ? '热销' : undefined
      }));

      setProducts(prevProducts => [...prevProducts, ...newProducts]);
      setPage(prevPage => prevPage + 1);
      setLoading(false);
    }, 1000);
  };

  // 设置IntersectionObserver监听滚动
  useEffect(() => {
    const options = {
      root: null,
      rootMargin: '0px',
      threshold: 0.1
    };

    observerRef.current = new IntersectionObserver((entries) => {
      const [entry] = entries;
      if (entry.isIntersecting && !loading) {
        loadMoreProducts();
      }
    }, options);

    const target = document.getElementById('loading-trigger');
    if (target) {
      observerRef.current.observe(target);
    }

    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, [loading]);

  return (
    <div className={styles['home-container']}>
      {/* 添加搜索框部分 */}
      <div className={styles['search-section']}>
        <SearchBox handleQuery={handleQuery} />
      </div>
      
      {/* 商品列表 */}
      <div className={styles['product-list']}>
        {products.map((product) => (
          <div key={product.id} className={styles['product-card']}>
            <LazyImage
              src={product.image}
              alt={product.title}
              className={styles['product-image']}
            />
            <div className={styles['product-info']}>
              <div className={styles['product-title']}>{product.title}</div>
              <div className={styles['product-price']}>¥{product.price}</div>
            </div>
          </div>
        ))}
        <div id="loading-trigger" style={{ width: '100%', height: '20px' }}>
          {loading && <div style={{ textAlign: 'center', padding: '10px', color: '#666' }}>加载中...</div>}
        </div>
      </div>
    </div>
  );
};

export default Home;